#
# simc-python
# extraordinarily minimalistic python library for interfacing with SimulationC-
# raft. SimulationCraft is SimulationCraft is a tool to explore combat mechani-
# cs in the popular MMO RPG World of Warcraft (tm) and can be downloaded at
# <http://code.google.com/p/simulationcraft/>
#
# simcraft.py was written by Dusknoir <dusknoir.net> and is not in any way aff-
# illiated with the developers  of SimulationCraft.  documentation can be found
# at <http://code.google.com/p/simc-python/>.
#

import re
from os.path import exists
from commands import getoutput

class Api:

    cache = {}

    def __init__(self, simc):
        """creates an instance of Api and localizes the directory containing
        a simcraft executable.

        The SimCraft executable location should be absolute.

        """

        if not exists(simc):
            raise Exception("Provided SimulationCraft executable doesn't exist.")

        self.simc = simc

    def raw_exec(self, **kwargs):
        """runs a simcraft parse with arguments "kwargs" and returns the
        raw results. raw_exec is used by nearly all other simc-python
        methods.

        """

        d = " ".join(["%s=%s" % (k,v) for k,v in kwargs.items()])

        if d in self.cache:
            return self.cache[d]
        else:
            o = getoutput("%s %s" % (self.simc, d))
            self.cache[d] = o
            return o

    def get_character_dps(self, region, realm, name):
        """fetches a character's estimated DPS."""

        return re.findall(
            "(\d+)  (.+)  %s" % name.title(),
            self.raw_exec(armory=",".join([region,realm,name]))
        )[0][0]

    def get_scale_factors(self, region, realm, name, *stats):
        """fetches a character's scale factors.

        acceptable stats: Int Spi SP Hit Crit Haste
        case is important at the moment!"""

        data = {}
        for stat in stats:
            data[stat.lower()] = re.findall(
                "(%s)=([0-9\.]+)" % stat,
                self.raw_exec(
                    armory=",".join([region,realm,name]),
                    calculate_scale_factors=1,
                    scale_only=",".join([s.lower() for s in stats]))
            )[0][1]
        
        return data
